package com.example.demo.chat;

import com.alibaba.fastjson.JSON;
import com.example.demo.chat.myhandler.ChatHandler;
import com.example.demo.chat.myhandler.ConnectionHandler;
import com.example.demo.chat.myhandler.JoinGroupHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;

public class WebSocketHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame textWebSocketFrame) throws Exception {
        System.out.println(textWebSocketFrame.text());
        try {
            Command command= JSON.parseObject(textWebSocketFrame.text(),Command.class);
            switch (CommandType.match(command.getCode())){
                case CONNECTION  : ConnectionHandler.execute(command,ctx) ;
                break;
                case CHAT: ChatHandler.execute(textWebSocketFrame,ctx);
                break;
                case JOIN_GROUP: JoinGroupHandler.execute(ctx);
                break;
                default : ctx.channel().writeAndFlush(Result.fail("code不支持"));
                break;
            }

        } catch (Exception e){
            ctx.channel().writeAndFlush(Result.fail(e.getMessage()));
        }

    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        super.exceptionCaught(ctx, cause);
    }

}
